module history_mod

  use netcdf
  use namelist_mod
  
  implicit none

  private
  public :: history_init
  public :: history_output

  integer :: time_varid, x_dimid, time_dimid
  integer :: x_varid, rho_varid, rho_exact_varid
  integer :: ncid 
  contains

  subroutine history_init()

    character(len=256) :: file_name
    
    file_name = trim(case_name) // '.nc'

    call check(nf90_create(file_name, NF90_CLOBBER, ncid))
    call check(nf90_def_dim(ncid, 'time', NF90_UNLIMITED, time_dimid))
    call check(nf90_def_var(ncid, 'time', nf90_int, [time_dimid], time_varid))
    call check(nf90_put_att(ncid, time_varid, 'units', 'seconds since 1970-01-01 00:00:00'))
    call check(nf90_put_att(ncid, time_varid, 'calendar','gregorian'))

    call check(nf90_def_dim(ncid, 'x', nx, x_dimid))
    call check(nf90_def_var(ncid, 'x', nf90_float, [x_dimid], x_varid))
    call check(nf90_def_var(ncid, 'rho', nf90_float, [x_dimid, time_dimid], rho_varid))
    call check(nf90_def_var(ncid, 'rho_exact', nf90_float, [x_dimid, time_dimid], rho_exact_varid))
   
    call check(nf90_enddef(ncid))
    call check(nf90_put_var(ncid, x_varid, x))
    call check(nf90_close(ncid))

  end subroutine history_init

  subroutine history_output(rho, rho_exact, time_step)
    
    real(r8), intent(in) :: rho(nx)
    real(r8), intent(in) :: rho_exact(nx)
    integer, intent(in) :: time_step
    character(len=256) :: file_name
    integer :: start(2), count(2)

    file_name = trim(case_name) // '.nc'

    call check(nf90_open(file_name, NF90_WRITE, ncid))  
    call check(nf90_inq_varid(ncid, 'time', time_varid)) 
    call check(nf90_put_var(ncid, time_varid, time_step, start=(/time_step/)))
    start = (/1, time_step/)
    count = (/nx, 1/)
    call check(nf90_inq_varid(ncid, 'rho', rho_varid)) 
    call check(nf90_put_var(ncid, rho_varid, rho, start=start, count=count))

    call check(nf90_inq_varid(ncid, 'rho_exact', rho_exact_varid)) 
    call check(nf90_put_var(ncid, rho_exact_varid, rho_exact, start=start, count=count))

    call check(nf90_close(ncid))

  end subroutine history_output

  subroutine check(status)

    integer, intent(in) :: status
    
    if (status /= nf90_noerr) then
      print*, trim(nf90_strerror(status))
      stop "netcdf stoped"
    end if

  end subroutine check

end module history_mod